﻿using ICMS.PluginInterfaces;
using SharpCompress.Archive;
using SharpCompress.Common;
using SharpCompress.Reader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace commonImportPlugin.Common
{
    /// <summary>
    /// 通用公共基础函数类
    /// </summary>
    public class CommonUtil
    {
        #region 实现该类单例模式

        //单例变量
        private static CommonUtil uniqueInstance;
        //线程锁
        private static object locker=new object();
        /// <summary>
        /// 单例
        /// </summary>
        /// <returns></returns>
        public static CommonUtil GetInstance()
        {
            if(uniqueInstance==null)
            {
                lock(locker)
                {
                    if (uniqueInstance == null)
                        uniqueInstance = new CommonUtil();           
                }
            }
            return uniqueInstance;
        }
        #endregion

        /// <summary>
        ///  将一list写入到文本
        /// （若filePath不存在建自动创建）
        /// </summary>
        /// <param name="listDatas">要写入的list<string></param>
        /// <param name="filePath">要写入的文件</param>
        /// <returns>true成功，false失败</returns>
        public bool ListStringToTxtFile(List<string> listDatas, string filePath)
        {
            try
            {
                //文件目录
                string fileDirectory = Path.GetDirectoryName(filePath);

                //判断目录是否存在
                if (!Directory.Exists(fileDirectory))
                    Directory.CreateDirectory(fileDirectory);

                //删除原有文件
                if (File.Exists(filePath))
                    File.Delete(filePath);

                //创建文件流
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);

                //写入
                foreach (string data in listDatas)
                {
                    sw.WriteLine(data);
                }

                //关闭
                sw.Close();
                fs.Close();

                return true;

            }
            catch 
            {
                return false; ;
            }
            
         
        }

        /// <summary>
        /// 判断程序是否继续，否则退出程序，并选中相应文件，是则程序继续往下执行
        /// </summary>
        /// <param name="showMessage">提示内容</param>
        /// <param name="selectFilePath">选中否后选中的文件</param>
        /// <param name="trueOrfalseOpenFile">ture打开文件还是false打开文件</param> 
        /// <returns>true 选中是，false选中否</returns>
        public bool WhetherContinue(string showMessage)
        {
            if (MessageBox.Show(showMessage, "是否继续", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将一string写入文本
        /// </summary>
        /// <param name="filePath">日志的路径</param>
        /// <param name="content">内容</param>
        public void StringToTxtFile(string filePath, string content)
        {
            //文件目录
            string directory = Path.GetDirectoryName(filePath);

            //判断目录是否存在
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            //写入
            File.WriteAllText(filePath, content);
        }

        /// <summary>
        /// 打开文件夹并选中相应文件
        /// </summary>
        /// <param name="fileFullName">所要选择的文件</param>
        public void OpenFolderAndSelectFile(String fileFullName)
        {
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
            psi.Arguments = "/e,/select," + fileFullName;
            System.Diagnostics.Process.Start(psi);
        }

        /// <summary>
        /// 截取字符串函数
        /// </summary>
        /// <param name="inputString">要截取的字符串</param>
        /// <param name="subStart">截取的起始位置(1表示第一位</param>
        /// <param name="subEnd">截取的结束位置(1表示第一位，-1表示倒数第一位）</param>
        /// <returns>结果</returns>
        public string SubString(string inputString, int subStart, int subEnd)
        {
            string result = "";//结果
            int finaSubEnd = 0;//实际结束位置

            if (subStart < 1)
                return "";
            //获取实际截取位置
            finaSubEnd = subEnd < 0 ? inputString.Length + subEnd - subStart + 2 : subEnd - subStart + 1;

            //截取字符
            result = inputString.Substring(subStart - 1, finaSubEnd);

            return result;
        }

        /// <summary>  
        /// 获取配置文件的路径  
        /// </summary>  
        /// <returns>配置文件路径</returns>  
        public string GetConfigPath()
        {
            string dllFilePath = Assembly.GetExecutingAssembly().CodeBase;//动态库路径
            string fileName = Path.GetFileName(dllFilePath);//动态库名字

            string configPath = dllFilePath.Replace(fileName, "config.xml");//配置文件路径

            return configPath;
        }

        /// <summary>
        /// 读取配置文件的值，将其放在Dictionary<string,string>中
        /// 配置文件的格式如：name:小明//姓名
        /// </summary>
        /// <param name="filePath">配置文件路径</param>
        /// <returns></returns>
        public Dictionary<string, string> ReadConfigFile(string filePath)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();//最总结果

            if (!File.Exists(filePath))//文件不存在
                throw new Exception(filePath + "文件不存在!");

            string[] originConfigs = File.ReadAllLines(filePath, Encoding.GetEncoding("GB2312"));

            try
            {
                foreach (string originConfig in originConfigs)
                {
                    if (string.IsNullOrEmpty(originConfig))
                        continue;
                    try
                    {
                        string keyId = originConfig.TrimStart().Remove(originConfig.IndexOf(':'));//获取配置项Id
                        string tempstring = originConfig.Replace(keyId + ":", "");//除去:前面的字符串
                        string value = tempstring.Remove(tempstring.IndexOf("//")).Trim();//获取配置值
                        result.Add(keyId, value);
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch
            {
                throw new Exception("读取配置文件：" + filePath + "失败");
            }
            return result;
        }

        /// <summary>
        /// 根据筛选文件筛选数据
        /// 内容格式：第一行备注信息，第二行以后格式：匹配项1+“,”+匹配项2）
        /// </summary>
        /// <param name="filterDatas">需筛选的数据</param>
        /// <param name="filterDataFilePath">筛选文件路径</param>
        /// <param name="filterItem">匹配项名字（值为：bankCardId,ssCardId,personId之1</param>
        /// <returns>最终结果</returns>
        public List<ICData> FilterDatasWithFile(List<ICData> filterDatas,string filterDataFilePath,string filterItem )
        {
            if (!File.Exists(filterDataFilePath))
                return filterDatas;

            //经过筛选后的数据
            List<ICData> afterFilterDatas = new List<ICData>();
              
            //读取所有数据
            string[] filterItems = File.ReadAllLines(filterDataFilePath);
      
            //收集所有匹配项
            #region
            string[] HeadItemParams = filterItems[0].Split(',');
            int filterItemIndex = 0;
            #region 获取过滤项Index
            for (int i = 0; i < HeadItemParams.Length; i++)
			{
			    if(HeadItemParams[i]==filterItem)
                {
                    filterItemIndex = i;
                    break;
                }
            }
            #endregion

            #region 收集过滤项
            List<string> filterIds=new List<string>();
            for (int i = 1; i < filterItems.Length; i++)
			{
               string Id = filterItems[i].Split(',')[filterItemIndex];
			   filterIds.Add(Id);
            }
            #endregion
            #endregion

            //根据相应Id过滤数据
            #region 
            afterFilterDatas =filterDatas.FindAll(delegate(ICData icData)
            {
                switch (filterItem)
                {
                    case "bankCardId"://根据银行卡号
                        if(filterIds.Contains(icData.BankCardID))
                        {
                            filterIds.Remove(icData.BankCardID);
                            return false;
                        }
                        return true;
                    case "personId"://根据身份证号
                        if(filterIds.Contains(icData.PersonID))
                        {
                            filterIds.Remove(icData.PersonID);
                            return false;
                        }
                        return true;;
                    case "ssCardId"://根据社保卡号号
                        if(filterIds.Contains(icData.SSCardID))
                        {
                            filterIds.Remove(icData.SSCardID);
                            return false;
                        }
                        return true;
                    default:
                        return true;
                }
            });
            #endregion

            return afterFilterDatas;
        }

        /// <summary>
        /// 生成导入成功日志文件
        /// createItems的值为：bankCardId，personId，ssCardId
        /// </summary>
        /// <param name="createItems">匹配项</param>
        /// <param name="datas">成功导入的数据</param>
        /// <param name="logFilePath">日志文件路径</param>
        /// <returns>true成功，false失败</returns>
        public bool CreateSucceedLogFile(string createItems, List<ICData> datas, string logFilePath)
        {
            string directory = Path.GetDirectoryName(logFilePath);

            string[] Items = createItems.Trim().Split('|');

            bool bankCardIdFlag = false;//银行卡号
            bool personIdFlag = false;//身份证号
            bool ssCardIdFlag = false;//社保卡号
            bool isInsertHead = false;//是否插入头

            string headItems = "";

            if (!File.Exists(logFilePath))
                isInsertHead = true;

            //生成项初始化
            #region 
            foreach (string item in Items)
            {
                switch (item)
                {
                    case "bankCardId":
                        headItems = "bankCardId";
                        bankCardIdFlag = true;
                        break;
                    case "personId":
                        headItems += ",personId";
                        personIdFlag = true;
                        break;
                    case "ssCardId":
                        headItems += ",ssCardId";
                        ssCardIdFlag = true;
                        break;
                    default:
                        break;
                }
            }
            #endregion

            //根据生成项生成
            if (bankCardIdFlag || personIdFlag || ssCardIdFlag)
            {
                #region 生成成功日志
                //不存在目录则建
                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                //初始化输入流
                FileStream fs = new FileStream(logFilePath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);

                if (isInsertHead)
                    sw.WriteLine(headItems.Trim(','));

                //写入
                foreach (ICData data in datas)
                {
                    string finalData = (bankCardIdFlag ? data.BankCardID : "");
                    finalData += (personIdFlag ? "," + data.PersonID : "");
                    finalData += (ssCardIdFlag ? "," + data.SSCardID : "");
                    finalData = finalData.Trim(',');
                    sw.WriteLine(finalData);
                }
                
                //关闭
                sw.Close();
                fs.Close();

                return true;
                #endregion
            }
            return false;
        }

        /// <summary>
        /// 读取sortId值应为多少
        /// </summary>
        /// <param name="logFilePath">成功日志文件</param>
        /// <returns>sortId值</returns>
        public int ReadSortIdValue(string logFilePath)
        {
            try
            {
                int sortId = 1;
                //文件不存在
                if (!File.Exists(logFilePath))
                    return sortId;

                sortId = File.ReadAllLines(logFilePath).Length;

                return sortId;
            }
            catch (Exception)
            {
                return 1;
            }       
        }

    }
}
